package cn.hznc.controller.service.program;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hznc.constant.CommonConstant;
import cn.hznc.controller.service.QuerySqlServerService;
import cn.hznc.controller.service.program.logic.SubProgramDo;
import cn.hznc.domain.entity.*;
import cn.hznc.domain.entity.common.EquipmentSubprogramMappingEntity;
import cn.hznc.domain.request.program.*;
import cn.hznc.dto.SubProgramImport;
import cn.hznc.mapper.*;
import cn.hznc.repository.AssemblyToolInventoryRepository;
import cn.hznc.repository.EquipmentGroupRepository;
import cn.hznc.controller.service.program.logic.SubProgramManageLogic;
import cn.hznc.repository.WarehouseRespository;
import cn.hznc.utils.CommonUtil;
import cn.hznc.utils.UUIDUtil;
import cn.hznc.vo.EquipmentGroupVo;
import cn.hznc.vo.ProgramVo;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 子程序服务
 *
 * @Author Administrator
 * @Date 2023/3/14 9:21
 */
@Service
@Slf4j
public class SubProgramManageService {
    @Resource
    private SubProgramMapper subProgramMapper;

    @Resource
    private ProgramMapper programMapper;

    @Resource
    private AssemblyToolInventoryMapper assemblyToolInventoryMapper;

    @Resource
    private EquipmentShankModelMapper equipmentShankModelMapper;

    @Resource
    private AssemblyToolInventoryRepository assemblyToolInventoryRepository;

    @Resource
    private QuerySqlServerService querySqlServerService;

    @Resource
    private EquipmentGroupRepository equipmentGroupRepository;

    @Resource
    private EquipmentSubprogramMappingMapper equipmentSubprogramMappingMapper;

    @Resource
    private WarehouseRespository warehouseRespository;

    @Resource
    private ProgramDurationTimeMapper programDurationTimeMapper;


    @Resource
    private MachineToolStatusMapper machineToolStatusMapper;

    @Resource
    private ProductionMapper productionMapper;

    @Resource
    private ShankModelMappingMapper shankModelMappingMapper;

    /**
     * 根据请求查询
     *
     * @param querySubProgramReq querySubProgramReq
     * @return
     */
    public List<SubProgramEntity> querySubProgramList(QuerySubProgramReq querySubProgramReq) {
        return querySubProgramList(querySubProgramReq.getProgramCode(), querySubProgramReq.getVersion(), querySubProgramReq.getEquipmentId(), querySubProgramReq.getFlag());
    }

    /**
     * 根据主程序和版本号查询
     *
     * @param programCode programCode
     * @param version     version
     * @return
     */
    public List<SubProgramEntity> querySubProgramList(String programCode, Integer version, Integer equipmentId, Integer flag) {
        List<SubProgramEntity> resultList = new ArrayList<>();
        QueryWrapper<EquipmentSubprogramMappingEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("program_code", programCode);
        wrapper.eq("equipment_id", equipmentId);
        EquipmentSubprogramMappingEntity mapping = equipmentSubprogramMappingMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(mapping)) {
            //印射表为空 直接返回
            return resultList;
        }
        QueryWrapper<SubProgramEntity> subProgramWrapper = new QueryWrapper<>();
        subProgramWrapper.eq("version", version);
        subProgramWrapper.eq("program_code", mapping.getProgramCode());
        if (ObjectUtil.isNotNull(flag) && flag == 0) {
            return subProgramMapper.selectList(subProgramWrapper);
        } else if (ObjectUtil.isNotNull(flag) && flag == 1) {
            return subProgramMapper.selectList(subProgramWrapper).stream().filter(distinctByKey1(SubProgramEntity::getToolCode)).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    static <T> Predicate<T> distinctByKey1(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

//    /**
//     * 根据主程序和版本号查询
//     *
//     * @param programCode programCode
//     * @param version     version
//     * @return
//     */
//    public List<Map<String, Object>> querySubProgramList(String programCode, Integer version) {
//        List<Map<String, Object>> resultList = new ArrayList<>();
//        List<String> groupTypes = checkSubProgramGroup();
//        groupTypes.forEach(s -> {
//            Map<String, Object> paramMap = new HashMap<>();
//            List<Map<String, Object>> singleResultList = new ArrayList<>();
//            //构建统一编辑机床程序
//            Map<String, Object> totalSingleParamMap = new HashMap<>();
//            totalSingleParamMap.put("equipmentId", null);
//            totalSingleParamMap.put("equipmentName", "全部");
//            totalSingleParamMap.put("singleList", new ArrayList<>());
//            totalSingleParamMap.put("flag", 0);
//            singleResultList.add(totalSingleParamMap);
//            List<Map<String, Object>> equipmentMap = equipmentGroupRepository.selectEquipMentByGroupType(s);
//            equipmentMap.forEach(stringObjectMap -> {
//                Map<String, Object> singleParamMap = new HashMap<>();
//                List<SubProgramEntity> subProgramEntities = querySubprogramList(programCode, version, s, (Integer) stringObjectMap.getOrDefault("equipmentId", null));
//                singleParamMap.put("equipmentId", stringObjectMap.get("equipmentId"));
//                singleParamMap.put("equipmentName", stringObjectMap.get("equipmentName"));
//                singleParamMap.put("singleList", subProgramEntities);
//                singleParamMap.put("flag", CollectionUtil.isEmpty(subProgramEntities) ? 0 : 1);
//                singleResultList.add(singleParamMap);
//            });
//            paramMap.put("groupType", s);
//            List<SubProgramEntity> checkIsEmpty = querySubprogramList(programCode, version, s, null);
//            paramMap.put("flag", CollectionUtil.isEmpty(checkIsEmpty) ? 0 : 1);
//            paramMap.put("list", singleResultList);
//            resultList.add(paramMap);
//        });
////        LambdaQueryWrapper<SubProgramEntity> wrapper = new LambdaQueryWrapper<>();
////        wrapper.orderByAsc(SubProgramEntity::getSeq);
////        wrapper.eq(SubProgramEntity::getProgramCode,programCode)
////                .eq(SubProgramEntity::getEquipmentGroupType ,groupType)
////                .eq(SubProgramEntity::getVersion,version);
////        List<SubProgramEntity> subProgramEntities = subProgramMapper.selectList(wrapper);
////        if (CollectionUtil.isEmpty(subProgramEntities)){
////            return Collections.emptyList();
////        }
//        return resultList;
//    }

    private List<SubProgramEntity> querySubprogramList(String programCode, Integer version) {
        LambdaQueryWrapper<SubProgramEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(SubProgramEntity::getSeq);
        wrapper.eq(SubProgramEntity::getProgramCode, programCode)
                .eq(SubProgramEntity::getVersion, version);
//                .eq(SubProgramEntity::getEquipmentGroupType, equipmentGroupType);
//        if (ObjectUtil.isNotNull(equipmentId)) {
//            wrapper.eq(SubProgramEntity::getEquipmentId, equipmentId);
//        }
        return subProgramMapper.selectList(wrapper);
    }

    /**
     * 批量编辑子程序
     *
     * @param addOrEditSubProgramReq addOrEditSubProgramReq
     * @return
     */
    public ProgramVo addOrEditSubProgram(AddOrEditSubProgramReq addOrEditSubProgramReq) {
        QueryWrapper<EquipmentSubprogramMappingEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("program_code", addOrEditSubProgramReq.getProgramCode());
        wrapper.eq("equipment_id", addOrEditSubProgramReq.getEquipmentId());
        EquipmentSubprogramMappingEntity equipmentSubprogramMappingEntity = equipmentSubprogramMappingMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(equipmentSubprogramMappingEntity)) {
            return new ProgramVo();
        }
        // 构造编辑，修改，删除业务所需要的参数
        List<SubProgramEntity> originSubProgramList = querySubprogramList(addOrEditSubProgramReq.getProgramCode(), addOrEditSubProgramReq.getProgramVersion());
        List<SubProgramEntity> updateSubProgramList = transferUpdateSubProgramList(addOrEditSubProgramReq, equipmentSubprogramMappingEntity.getProgramCode());
        SubProgramManageLogic subProgramManageLogic = new SubProgramManageLogic(originSubProgramList, updateSubProgramList);
        subProgramManageLogic.buildSubProgramDo();
        SubProgramDo subProgramDo = subProgramManageLogic.getSubProgramDo();
        // 数据持久化
        persistance(subProgramDo);
        // 暂时不涉及升级版本的问题
        return new ProgramVo(addOrEditSubProgramReq.getProgramCode(), addOrEditSubProgramReq.getProgramVersion());
    }

    /**
     * 批量编辑子程序
     *
     * @param addOrEditSubProgramReq addOrEditSubProgramReq
     * @return
     */
    public ProgramVo addOrEditSubProgramReload(AddOrEditSubProgramReq addOrEditSubProgramReq) {
        QueryWrapper<EquipmentSubprogramMappingEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("program_code", addOrEditSubProgramReq.getProgramCode());
        wrapper.eq("equipment_id", addOrEditSubProgramReq.getEquipmentId());
        EquipmentSubprogramMappingEntity equipmentSubprogramMappingEntity = equipmentSubprogramMappingMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(equipmentSubprogramMappingEntity)) {
            return new ProgramVo();
        }
        // 构造编辑，修改，删除业务所需要的参数
        List<SubProgramEntity> updateSubProgramList = transferUpdateSubProgramList(addOrEditSubProgramReq, equipmentSubprogramMappingEntity.getProgramCode());
        SubProgramManageLogic subProgramManageLogic = new SubProgramManageLogic(new ArrayList<>(), updateSubProgramList);
        subProgramManageLogic.buildSubProgramDo();
        SubProgramDo subProgramDo = subProgramManageLogic.getSubProgramDo();
        // 数据持久化
        persistance(subProgramDo);
        // 暂时不涉及升级版本的问题
        return new ProgramVo(addOrEditSubProgramReq.getProgramCode(), addOrEditSubProgramReq.getProgramVersion());
    }


    private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    private void persistance(SubProgramDo subProgramDo) {
        // 删除
        List<Integer> deleteIds = subProgramDo.getDeleteElement().stream().map(SubProgramEntity::getId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(deleteIds)) {
            List<String> toolNos = subProgramDo.getDeleteElement().stream().map(SubProgramEntity::getToolCode).collect(Collectors.toList());
            assemblyToolInventoryRepository.deleteBatchByToolNo(toolNos);
            subProgramMapper.deleteBatchIds(deleteIds);
        }
        // 新增
        if (CollectionUtil.isNotEmpty(subProgramDo.getCreateElement())) {
            List<AssemblyToolInventoryEntity> existRecord = assemblyToolInventoryMapper.selectList(new QueryWrapper<>());
            List<String> existToolNo = existRecord.stream().map(AssemblyToolInventoryEntity::getToolNo).collect(Collectors.toList());
            //existToolNo

//            subProgramDo.getCreateElement().stream().filter(subProgramEntity -> ).forEach(subProgramEntity -> {
//                AssemblyToolInventoryEntity assemblyToolInventoryEntity = new AssemblyToolInventoryEntity();
//                assemblyToolInventoryEntity.getToolNo()
//            });
            subProgramMapper.insertBatchSomeColumn(subProgramDo.getCreateElement());
        }
        // 修改
        if (CollectionUtil.isNotEmpty(subProgramDo.getUpdateElement())) {
            subProgramMapper.updateBatchById(subProgramDo.getUpdateElement());
        }
    }

    private List<SubProgramEntity> transferUpdateSubProgramList(AddOrEditSubProgramReq addOrEditSubProgramReq, String programCode) {
        if (CollectionUtil.isEmpty(addOrEditSubProgramReq.getBatchUpdateReq())) {
            return Collections.emptyList();
        }
        List<SubProgramEntity> updateSubProgramList = new ArrayList<>();
        for (int i = 0; i < addOrEditSubProgramReq.getBatchUpdateReq().size(); i++) {
            SubProgramEntity subProgramEntity = new SubProgramEntity();
            BeanUtil.copyProperties(addOrEditSubProgramReq.getBatchUpdateReq().get(i), subProgramEntity);
            // 重新生成自增序列
            subProgramEntity.setSeq(i + 1);
            if (ObjectUtil.isNull(addOrEditSubProgramReq.getBatchUpdateReq().get(i).getId())) {
                // 新增的重新生成
                subProgramEntity.setProgramCode(addOrEditSubProgramReq.getProgramCode());
                subProgramEntity.setVersion(addOrEditSubProgramReq.getProgramVersion());
                subProgramEntity.setCode("subProgram" + "-" + UUIDUtil.getUUID());
                //subProgramEntity.setMappingId(mappingId);
            }
            updateSubProgramList.add(subProgramEntity);
        }
//        //获取该分类的机床id
//        List<Integer> ids = equipmentGroupRepository.selectByGroupType(addOrEditSubProgramReq.getGroupType());
//        if (ObjectUtil.isNotNull(addOrEditSubProgramReq.getEquipmentId())) {
//            //机床id不为空则根据机床id过滤
//            ids = ids.stream().filter(integer -> Objects.equals(integer, addOrEditSubProgramReq.getEquipmentId())).collect(Collectors.toList());
//        }
//        //生成对应数量的子程序
//        ids.forEach(integer -> {
//            for (int i = 0; i < addOrEditSubProgramReq.getBatchUpdateReq().size(); i++) {
//                SubProgramEntity subProgramEntity = new SubProgramEntity();
//                BeanUtil.copyProperties(addOrEditSubProgramReq.getBatchUpdateReq().get(i), subProgramEntity);
//                // 重新生成自增序列
//                subProgramEntity.setSeq(i + 1);
//                if (ObjectUtil.isNull(addOrEditSubProgramReq.getBatchUpdateReq().get(i).getId())) {
//                    // 新增的重新生成
//                    subProgramEntity.setProgramCode(addOrEditSubProgramReq.getProgramCode());
//                    subProgramEntity.setVersion(addOrEditSubProgramReq.getProgramVersion());
//                    subProgramEntity.setCode("subProgram" + "-" + UUIDUtil.getUUID());
////                    subProgramEntity.setEquipmentGroupType(addOrEditSubProgramReq.getGroupType());
////                    subProgramEntity.setEquipmentId(integer);
//                }
//                updateSubProgramList.add(subProgramEntity);
//            }
//        });
        return updateSubProgramList;
    }

    private List<SubProgramEntity> transferUpdateSubProgramList(List<SingleSubProgramReq> batchUpdateReq, String programCode, Integer version, Integer mappingId) {
        if (CollectionUtil.isEmpty(batchUpdateReq)) {
            return Collections.emptyList();
        }
        List<SubProgramEntity> updateSubProgramList = new ArrayList<>();
        for (int i = 0; i < batchUpdateReq.size(); i++) {
            SubProgramEntity subProgramEntity = new SubProgramEntity();
            BeanUtil.copyProperties(batchUpdateReq.get(i), subProgramEntity);
            // 重新生成自增序列
            subProgramEntity.setSeq(i + 1);
            if (ObjectUtil.isNull(batchUpdateReq.get(i).getId())) {
                // 新增的重新生成
                subProgramEntity.setProgramCode(programCode);
                subProgramEntity.setVersion(version);
                subProgramEntity.setCode("subProgram" + "-" + UUIDUtil.getUUID());
                subProgramEntity.setMappingId(mappingId);
            }
            updateSubProgramList.add(subProgramEntity);
        }
//        //获取该分类的机床id
//        List<Integer> ids = equipmentGroupRepository.selectByGroupType(addOrEditSubProgramReq.getGroupType());
//        if (ObjectUtil.isNotNull(addOrEditSubProgramReq.getEquipmentId())) {
//            //机床id不为空则根据机床id过滤
//            ids = ids.stream().filter(integer -> Objects.equals(integer, addOrEditSubProgramReq.getEquipmentId())).collect(Collectors.toList());
//        }
//        //生成对应数量的子程序
//        ids.forEach(integer -> {
//            for (int i = 0; i < addOrEditSubProgramReq.getBatchUpdateReq().size(); i++) {
//                SubProgramEntity subProgramEntity = new SubProgramEntity();
//                BeanUtil.copyProperties(addOrEditSubProgramReq.getBatchUpdateReq().get(i), subProgramEntity);
//                // 重新生成自增序列
//                subProgramEntity.setSeq(i + 1);
//                if (ObjectUtil.isNull(addOrEditSubProgramReq.getBatchUpdateReq().get(i).getId())) {
//                    // 新增的重新生成
//                    subProgramEntity.setProgramCode(addOrEditSubProgramReq.getProgramCode());
//                    subProgramEntity.setVersion(addOrEditSubProgramReq.getProgramVersion());
//                    subProgramEntity.setCode("subProgram" + "-" + UUIDUtil.getUUID());
////                    subProgramEntity.setEquipmentGroupType(addOrEditSubProgramReq.getGroupType());
////                    subProgramEntity.setEquipmentId(integer);
//                }
//                updateSubProgramList.add(subProgramEntity);
//            }
//        });
        return updateSubProgramList;
    }

    public void importProgramBroad(List<SubProgramImport> importData) {
        ProgramEntity programEntity = new ProgramEntity();
        programEntity.setName("主程序" + UUIDUtil.getUUID().substring(0, 7));
        programEntity.setVersion(CommonConstant.INIT_VERSION);
        String proCode = "program-" + UUIDUtil.getUUID();
        programEntity.setCode(proCode);
        programMapper.insert(programEntity);
        List<AssemblyToolInventoryEntity> assemblyToolInventoryEntities = new ArrayList<>();
        List<AssemblyToolInventoryEntity> originalList = assemblyToolInventoryMapper.selectList(new QueryWrapper<>());
        List<String> originalToolNoList = originalList.stream().map(AssemblyToolInventoryEntity::getToolNo).collect(Collectors.toList());
        List<SubProgramEntity> insertList = importData.stream().map(subProgramImport -> {
            SubProgramEntity subProgramEntity = new SubProgramEntity();
            BeanUtils.copyProperties(subProgramImport, subProgramEntity);
            subProgramEntity.setProgramCode(proCode);
            subProgramEntity.setCode("subProgram-" + UUIDUtil.getUUID());
            subProgramEntity.setVersion(1);
            AssemblyToolInventoryEntity assemblyToolInventoryEntity = new AssemblyToolInventoryEntity();
            assemblyToolInventoryEntity.setToolNo(subProgramImport.getToolCode());
            assemblyToolInventoryEntity.setToolType(subProgramImport.getToolModel());
            assemblyToolInventoryEntity.setToolNumber(1);
            assemblyToolInventoryEntity.setShankType(subProgramImport.getShankModel());
            assemblyToolInventoryEntity.setShankNumber(1);
            assemblyToolInventoryEntity.setName("总成" + System.currentTimeMillis() + UUIDUtil.getUUID().substring(0, 5));
            if (!originalToolNoList.contains(assemblyToolInventoryEntity.getToolNo())) {
                assemblyToolInventoryEntities.add(assemblyToolInventoryEntity);
            }
            return subProgramEntity;
        }).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(insertList)) {
            subProgramMapper.insertBatchSomeColumn(insertList);
        }
        if (CollectionUtil.isNotEmpty(assemblyToolInventoryEntities)) {
            assemblyToolInventoryMapper.insertBatchSomeColumn(assemblyToolInventoryEntities);
        }

    }

    public List<String> checkSubProgramGroup() {
        List<String> strings = equipmentGroupRepository.selectGroupType();
        return strings;
    }

    public Object checkSubProgram(String programCode, String groupType) {

        return null;
    }

    public List<Integer> selectEquipmentIds() {
        return equipmentGroupRepository.selectEquipmentIds();
    }

    public Object abutmentSubProgram() {
        List<AbutmentProgramEntity> abutmentPrograms = querySqlServerService.abutmentSubProgramReload();
        if (CollectionUtil.isNotEmpty(abutmentPrograms)) {
            List<ProgramEntity> addProgramEntities = new ArrayList<>();
            List<ProgramEntity> updateProgramEntities = new ArrayList<>();
            List<SubProgramEntity> addSubProgramEntities = new ArrayList<>();
            List<Integer> deleteSubProgramEntities = new ArrayList<>();
            abutmentPrograms.forEach(abutmentProgram -> {
                //查询数据库中是否有该条主程序记录
                QueryWrapper<ProgramEntity> wrapper = new QueryWrapper<>();
                wrapper.eq("program_cn", abutmentProgram.getProgramCn());
                ProgramEntity existProgramEntity = programMapper.selectOne(wrapper);
                String programCode = "program-" + UUIDUtil.getUUID();
                if (ObjectUtil.isNotNull(existProgramEntity)) {
                    programCode = existProgramEntity.getCode();
                    existProgramEntity.setProgramNum(abutmentProgram.getMaterialNo());
                    existProgramEntity.setName(abutmentProgram.getProductionNum());
                    existProgramEntity.setVersion(CommonConstant.INIT_VERSION);
                    BeanUtil.copyProperties(abutmentProgram, existProgramEntity);
                    updateProgramEntities.add(existProgramEntity);
                    QueryWrapper<SubProgramEntity> subProgramWrapper = new QueryWrapper<>();
                    subProgramWrapper.eq("program_code", programCode);
                    List<SubProgramEntity> subProgramEntityList = subProgramMapper.selectList(subProgramWrapper);
                    if (CollectionUtil.isNotEmpty(subProgramEntityList)) {
                        deleteSubProgramEntities.addAll(subProgramEntityList.stream().map(SubProgramEntity::getId).collect(Collectors.toList()));
                    }
                } else {
                    ProgramEntity programEntity = new ProgramEntity();
                    programEntity.setCode(programCode);
                    programEntity.setProgramNum(abutmentProgram.getMaterialNo());
                    programEntity.setName(abutmentProgram.getProductionNum());
                    programEntity.setVersion(CommonConstant.INIT_VERSION);
                    BeanUtil.copyProperties(abutmentProgram, programEntity);
                    addProgramEntities.add(programEntity);
                }
                List<AbutmentSubProgramEntity> connectSubProgram = abutmentProgram.getConnectSubProgram();
                if (CollectionUtil.isNotEmpty(connectSubProgram)) {
                    //根据关联机床构建子程序
                    List<Integer> equipmentIds = equipmentGroupRepository.selectEquipmentIds();
                    if (ObjectUtil.isNotNull(abutmentProgram.getEquipment()) || StringUtil.isNotEmpty(abutmentProgram.getEquipment())) {
                        //TO DO主程序适用机床不为空，则根据印射规则获取机床id
                    }
                    for (int i = 0; i < connectSubProgram.size(); i++) {
                        for (int j = 0; j < equipmentIds.size(); j++) {
                            AbutmentSubProgramEntity abutmentSubProgram = connectSubProgram.get(i);
                            SubProgramEntity subProgramEntity = new SubProgramEntity();
                            subProgramEntity.setCode("subProgram" + "-" + UUIDUtil.getUUID());
                            subProgramEntity.setProgramCode(programCode);
                            subProgramEntity.setVersion(CommonConstant.INIT_VERSION);
//                                subProgramEntity.setEquipmentId(equipmentIds.get(j));
//                                subProgramEntity.setEquipmentGroupType(equipmentGroupRepository.selectGroupTypeByEquipmentId(equipmentIds.get(j)));
                            subProgramEntity.setRpm(Integer.valueOf(abutmentSubProgram.getRpm()));
                            subProgramEntity.setFeed(new BigDecimal(abutmentSubProgram.getFeed()));
                            subProgramEntity.setExtension(new BigDecimal(abutmentSubProgram.getExtension()));
                            //BeanUtil.copyProperties(connectSubProgram.get(i) , subProgramEntity);
                            addSubProgramEntities.add(subProgramEntity);
                        }
                    }
                }
            });
            //批量新增主程序
            if (CollectionUtil.isNotEmpty(addProgramEntities)) {
                programMapper.insertBatchSomeColumn(addProgramEntities);
            }
            //批量修改主程序
            if (CollectionUtil.isNotEmpty(updateProgramEntities)) {
                programMapper.updateBatchById(updateProgramEntities);
            }
            //批量删除子程序
            if (CollectionUtil.isNotEmpty(deleteSubProgramEntities)) {
                programMapper.deleteBatchIds(deleteSubProgramEntities);
            }
            //批量新增子程序
            if (CollectionUtil.isNotEmpty(addSubProgramEntities)) {
                subProgramMapper.insertBatchSomeColumn(addSubProgramEntities);
            }
        }
        return Boolean.TRUE;
    }

    @DSTransactional
    public Object abutmentSubProgramReload1(List<Map<String, String>> materialNos) {
        List<AbutmentProgramEntity> abutmentPrograms = querySqlServerService.abutmentSubProgramReload1(materialNos);
        if (CollectionUtil.isNotEmpty(abutmentPrograms)) {
            List<ProgramEntity> addProgramEntities = new ArrayList<>();
            List<ProgramEntity> updateProgramEntities = new ArrayList<>();
            List<SubProgramEntity> addSubProgramEntities = new ArrayList<>();
            List<Integer> deleteSubProgramEntities = new ArrayList<>();
            List<EquipmentSubprogramMappingEntity> addMappingEntities = new ArrayList<>();
            abutmentPrograms.forEach(abutmentProgram -> {
                //查询数据库中是否有该条主程序记录
                QueryWrapper<ProgramEntity> wrapper = new QueryWrapper<>();
                wrapper.eq("program_cn", abutmentProgram.getProgramCn());
                ProgramEntity existProgramEntity = programMapper.selectOne(wrapper);
                String programCode = "program-" + UUIDUtil.getUUID();
                if (ObjectUtil.isNotNull(existProgramEntity)) {
                    programCode = existProgramEntity.getCode();
                    existProgramEntity.setProgramNum(abutmentProgram.getMaterialNo());
                    existProgramEntity.setName(abutmentProgram.getProductionNum());
                    existProgramEntity.setVersion(CommonConstant.INIT_VERSION);
                    BeanUtil.copyProperties(abutmentProgram, existProgramEntity);
                    updateProgramEntities.add(existProgramEntity);
                    QueryWrapper<SubProgramEntity> subProgramWrapper = new QueryWrapper<>();
                    subProgramWrapper.eq("program_code", programCode);
                    List<SubProgramEntity> subProgramEntityList = subProgramMapper.selectList(subProgramWrapper);
                    if (CollectionUtil.isNotEmpty(subProgramEntityList)) {
                        deleteSubProgramEntities.addAll(subProgramEntityList.stream().map(SubProgramEntity::getId).collect(Collectors.toList()));
                    }
                } else {
                    ProgramEntity programEntity = new ProgramEntity();
                    programEntity.setCode(programCode);
                    programEntity.setProgramNum(abutmentProgram.getMaterialNo());
                    programEntity.setName(abutmentProgram.getProductionNum());
                    programEntity.setVersion(CommonConstant.INIT_VERSION);
                    BeanUtil.copyProperties(abutmentProgram, programEntity);
                    addProgramEntities.add(programEntity);
                }
                List<AbutmentSubProgramEntity> connectSubProgram = abutmentProgram.getConnectSubProgram();
                if (CollectionUtil.isNotEmpty(connectSubProgram)) {
                    //根据关联机床构建子程序
                    List<Integer> equipmentIds = equipmentGroupRepository.selectEquipmentIds();
                    //查询是否需要往印射表中添加关联关系
                    QueryWrapper<EquipmentSubprogramMappingEntity> wrapper1 = new QueryWrapper<>();
                    wrapper1.eq("program_code", programCode);
                    List<EquipmentSubprogramMappingEntity> existMapping = equipmentSubprogramMappingMapper.selectList(wrapper1);
                    if (CollectionUtil.isNotEmpty(equipmentIds) && CollectionUtil.isEmpty(existMapping)) {
                        for (int i = 0; i < equipmentIds.size(); i++) {
                            Integer equipmentId = equipmentIds.get(i);
                            EquipmentSubprogramMappingEntity equipmentSubprogramMappingEntity = new EquipmentSubprogramMappingEntity();
                            equipmentSubprogramMappingEntity.setEquipmentId(equipmentId);
                            equipmentSubprogramMappingEntity.setProgramCode(programCode);
                            equipmentSubprogramMappingEntity.setCreateTime(new Date());
                            equipmentSubprogramMappingEntity.setEquipmentName(warehouseRespository.getNameByWarehouseId(equipmentId));
                            addMappingEntities.add(equipmentSubprogramMappingEntity);
                        }
                    }
                    //查询是否有标志位
                    int flag = 0;
                    for (int i = 0; i < connectSubProgram.size(); i++) {
                        if(StringUtils.isNotBlank(connectSubProgram.get(i).getBz()) && connectSubProgram.get(i).getBz().equals("1")){
                            //有标志位
                            flag = i + 1;
                            break;
                        }
                    }
                    //持久化子程序
                    if(flag != 0){
                        //分割list并持久化
                        persistSubProgram(addSubProgramEntities, programCode, connectSubProgram.subList(0, flag) , CommonConstant.INIT_VERSION);
                        persistSubProgram(addSubProgramEntities, programCode, connectSubProgram.subList(flag, connectSubProgram.size()) , 2);
                    }else{
                        persistSubProgram(addSubProgramEntities, programCode, connectSubProgram , CommonConstant.INIT_VERSION);
                    }

                }

            });
            //批量新增主程序
            if (CollectionUtil.isNotEmpty(addProgramEntities)) {
                programMapper.insertBatchSomeColumn(addProgramEntities);
            }
            //批量修改主程序
            if (CollectionUtil.isNotEmpty(updateProgramEntities)) {
                programMapper.updateBatchById(updateProgramEntities);
            }
            //批量删除子程序
            if (CollectionUtil.isNotEmpty(deleteSubProgramEntities)) {
                subProgramMapper.deleteBatchIds(deleteSubProgramEntities);
            }
            //批量新增子程序
            if (CollectionUtil.isNotEmpty(addSubProgramEntities)) {
                subProgramMapper.insertBatchSomeColumn(addSubProgramEntities);
            }
            //批量新增主程序和机床印射关系
            if (CollectionUtil.isNotEmpty(addMappingEntities)) {
                equipmentSubprogramMappingMapper.insertBatchSomeColumn(addMappingEntities);
            }
        }
        return Boolean.TRUE;
    }

    private  void persistSubProgram(List<SubProgramEntity> addSubProgramEntities, String programCode, List<AbutmentSubProgramEntity> connectSubProgram, Integer version) {
        for (int i = 0; i < connectSubProgram.size(); i++) {
            AbutmentSubProgramEntity abutmentSubProgram = connectSubProgram.get(i);
            SubProgramEntity subProgramEntity = new SubProgramEntity();
            subProgramEntity.setName(abutmentSubProgram.getName());
            subProgramEntity.setCode("subProgram" + "-" + UUIDUtil.getUUID());
            subProgramEntity.setProgramCode(programCode);
            subProgramEntity.setVersion(version);
            try {
                subProgramEntity.setRpm(Integer.valueOf(abutmentSubProgram.getRpm()));
            } catch (Exception e) {

            }
            try {
                subProgramEntity.setFeed(new BigDecimal(abutmentSubProgram.getFeed()));
            } catch (Exception e) {

            }
            try {
                subProgramEntity.setExtension(new BigDecimal(abutmentSubProgram.getExtension()));
            } catch (Exception e) {

            }
            try {
                subProgramEntity.setSeq(abutmentSubProgram.getSeq());
            } catch (Exception e) {

            }
            try {
                subProgramEntity.setToolCode(abutmentSubProgram.getToolCode());
            } catch (Exception e) {

            }
            try {
                subProgramEntity.setToolModel(abutmentSubProgram.getToolModel());
            } catch (Exception e) {

            }
            try {
                subProgramEntity.setShankModel(abutmentSubProgram.getShankModel());
            } catch (Exception e) {

            }
            addSubProgramEntities.add(subProgramEntity);
        }
    }

    @DSTransactional
    public Object abutmentSubProgramReload(List<String> materialNos) {
        List<AbutmentProgramEntity> abutmentPrograms = querySqlServerService.abutmentSubProgramReload(materialNos);
        if (CollectionUtil.isNotEmpty(abutmentPrograms)) {
            List<ProgramEntity> addProgramEntities = new ArrayList<>();
            List<ProgramEntity> updateProgramEntities = new ArrayList<>();
            List<SubProgramEntity> addSubProgramEntities = new ArrayList<>();
            List<Integer> deleteSubProgramEntities = new ArrayList<>();
            List<EquipmentSubprogramMappingEntity> addMappingEntities = new ArrayList<>();
            List<EquipmentSubprogramMappingEntity> deleteMappingEntities = new ArrayList<>();
            abutmentPrograms.forEach(abutmentProgram -> {
                //查询数据库中是否有该条主程序记录
                QueryWrapper<ProgramEntity> wrapper = new QueryWrapper<>();
                wrapper.eq("program_num", abutmentProgram.getMaterialNo());
                ProgramEntity existProgramEntity = programMapper.selectOne(wrapper);
                String programCode = "program-" + UUIDUtil.getUUID();
                if (ObjectUtil.isNotNull(existProgramEntity)) {
                    programCode = existProgramEntity.getCode();
                    existProgramEntity.setProgramNum(abutmentProgram.getMaterialNo());
                    existProgramEntity.setName(abutmentProgram.getProductionNum());
                    existProgramEntity.setVersion(CommonConstant.INIT_VERSION);
                    BeanUtil.copyProperties(abutmentProgram, existProgramEntity);
                    updateProgramEntities.add(existProgramEntity);
                    QueryWrapper<SubProgramEntity> subProgramWrapper = new QueryWrapper<>();
                    subProgramWrapper.eq("program_code", programCode);
                    List<SubProgramEntity> subProgramEntityList = subProgramMapper.selectList(subProgramWrapper);
                    if (CollectionUtil.isNotEmpty(subProgramEntityList)) {
                        deleteSubProgramEntities.addAll(subProgramEntityList.stream().map(SubProgramEntity::getId).collect(Collectors.toList()));
                    }
                    QueryWrapper<EquipmentSubprogramMappingEntity> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("program_code", existProgramEntity.getCode());
                    List<EquipmentSubprogramMappingEntity> existMappingList = equipmentSubprogramMappingMapper.selectList(queryWrapper);
                    if (CollectionUtil.isNotEmpty(existMappingList)) {
                        deleteMappingEntities.addAll(existMappingList);
                    }
                } else {
                    ProgramEntity programEntity = new ProgramEntity();
                    programEntity.setCode(programCode);
                    programEntity.setProgramNum(abutmentProgram.getMaterialNo());
                    programEntity.setName(abutmentProgram.getProductionNum());
                    programEntity.setVersion(CommonConstant.INIT_VERSION);
                    BeanUtil.copyProperties(abutmentProgram, programEntity);
                    addProgramEntities.add(programEntity);
                }
                List<AbutmentSubProgramEntity> connectSubProgram = abutmentProgram.getConnectSubProgram();
                if (CollectionUtil.isNotEmpty(connectSubProgram)) {
                    //根据关联机床构建子程序
                    List<Integer> equipmentIds = equipmentGroupRepository.selectEquipmentIds();
                    //往印射表中添加关联关系
                    if (CollectionUtil.isNotEmpty(equipmentIds)) {
                        for (int i = 0; i < equipmentIds.size(); i++) {
                            Integer equipmentId = equipmentIds.get(i);
                            EquipmentSubprogramMappingEntity equipmentSubprogramMappingEntity = new EquipmentSubprogramMappingEntity();
                            equipmentSubprogramMappingEntity.setEquipmentId(equipmentId);
                            equipmentSubprogramMappingEntity.setProgramCode(programCode);
                            equipmentSubprogramMappingEntity.setCreateTime(new Date());
                            equipmentSubprogramMappingEntity.setEquipmentName(warehouseRespository.getNameByWarehouseId(equipmentId));
                            addMappingEntities.add(equipmentSubprogramMappingEntity);
                        }
                    }
                    //持久化子程序
                    for (int i = 0; i < connectSubProgram.size(); i++) {
                        AbutmentSubProgramEntity abutmentSubProgram = connectSubProgram.get(i);
                        SubProgramEntity subProgramEntity = new SubProgramEntity();
                        subProgramEntity.setName(abutmentSubProgram.getName());
                        subProgramEntity.setCode("subProgram" + "-" + UUIDUtil.getUUID());
                        subProgramEntity.setProgramCode(programCode);
                        subProgramEntity.setVersion(CommonConstant.INIT_VERSION);
                        try {
                            subProgramEntity.setRpm(Integer.valueOf(abutmentSubProgram.getRpm()));
                        } catch (Exception e) {

                        }
                        try {
                            subProgramEntity.setFeed(new BigDecimal(abutmentSubProgram.getFeed()));
                        } catch (Exception e) {

                        }
                        try {
                            subProgramEntity.setExtension(new BigDecimal(abutmentSubProgram.getExtension()));
                        } catch (Exception e) {

                        }
                        try {
                            subProgramEntity.setSeq(abutmentSubProgram.getSeq());
                        } catch (Exception e) {

                        }
                        try {
                            subProgramEntity.setToolCode(abutmentSubProgram.getToolCode());
                        } catch (Exception e) {

                        }
                        try {
                            subProgramEntity.setToolModel(abutmentSubProgram.getToolModel());
                        } catch (Exception e) {

                        }
                        try {
                            subProgramEntity.setShankModel(abutmentSubProgram.getShankModel());
                        } catch (Exception e) {

                        }
                        addSubProgramEntities.add(subProgramEntity);
                    }
                }

            });
            //批量新增主程序
            if (CollectionUtil.isNotEmpty(addProgramEntities)) {
                programMapper.insertBatchSomeColumn(addProgramEntities);
            }
            //批量修改主程序
            if (CollectionUtil.isNotEmpty(updateProgramEntities)) {
                programMapper.updateBatchById(updateProgramEntities);
            }
            //批量删除子程序
            if (CollectionUtil.isNotEmpty(deleteSubProgramEntities)) {
                subProgramMapper.deleteBatchIds(deleteSubProgramEntities);
            }
            //批量新增子程序
            if (CollectionUtil.isNotEmpty(addSubProgramEntities)) {
                subProgramMapper.insertBatchSomeColumn(addSubProgramEntities);
            }
            //批量新增主程序和机床印射关系
            if (CollectionUtil.isNotEmpty(addMappingEntities)) {
                equipmentSubprogramMappingMapper.insertBatchSomeColumn(addMappingEntities);
            }
            //批量删除主程序和机床印射关系
            if (CollectionUtil.isNotEmpty(deleteMappingEntities)) {
                equipmentSubprogramMappingMapper.deleteBatchIds(deleteMappingEntities);
            }
        }
        return Boolean.TRUE;
    }


    public Object editEquipmentShankModel(EquipmentShankModelEntity equipmentShankModelEntity) {
        if (ObjectUtil.isNotNull(equipmentShankModelEntity.getId())) {
            //修改
            equipmentShankModelMapper.updateById(equipmentShankModelEntity);
            return Boolean.TRUE;
        }
        equipmentShankModelMapper.insert(equipmentShankModelEntity);
        return Boolean.TRUE;
    }

    public EquipmentShankModelEntity qryShankModelByEquipmentGroup(Integer equipmentId) {
        return equipmentGroupRepository.selectShankModel(equipmentId);
    }

    public Object saveAsNewProgram(SaveAsProgramReq saveAsProgramReq) {
        //新建关联关系
        EquipmentSubprogramMappingEntity equipmentSubprogramMappingEntity = new EquipmentSubprogramMappingEntity();
        equipmentSubprogramMappingEntity.setEquipmentId(saveAsProgramReq.getEquipmentId());
        equipmentSubprogramMappingEntity.setEquipmentName(warehouseRespository.getNameByWarehouseId(saveAsProgramReq.getEquipmentId()));
        equipmentSubprogramMappingEntity.setCreateTime(new Date());

        //新建主程序
        ProgramEntity programEntity = new ProgramEntity();
        String programCode = "program" + "-" + UUIDUtil.getUUID();
        BeanUtils.copyProperties(saveAsProgramReq.getProgram(), programEntity);
        programEntity.setCode(programCode);
        programEntity.setProgramNum(programEntity.getProgramNum() + "-" + warehouseRespository.getNameByWarehouseId(saveAsProgramReq.getEquipmentId()));
        programMapper.insert(programEntity);
        equipmentSubprogramMappingEntity.setProgramCode(programCode);
        equipmentSubprogramMappingMapper.insert(equipmentSubprogramMappingEntity);

        //新建子程序
        List<SubProgramEntity> subProgramEntityList = transferUpdateSubProgramList(saveAsProgramReq.getBatchUpdateReq(), programCode, saveAsProgramReq.getProgram().getVersion(), equipmentSubprogramMappingEntity.getId());
        if (CollectionUtil.isNotEmpty(subProgramEntityList)) {
            subProgramMapper.insertBatchSomeColumn(subProgramEntityList);
        }
        return Boolean.TRUE;
    }

    public Object qryEquipmentIds() {
        List<EquipmentGroupVo> resultList = new ArrayList<>();
        List<String> groupTypes = checkSubProgramGroup();
        if (CollectionUtil.isNotEmpty(groupTypes)) {
            groupTypes.forEach(s -> {
                EquipmentGroupVo equipmentGroupVo = new EquipmentGroupVo();
                equipmentGroupVo.setGroupType(s);
                equipmentGroupVo.setEquipments(equipmentGroupRepository.selectEquipMentByGroupType(s));
                resultList.add(equipmentGroupVo);
            });
        }
        return resultList;
    }

    public Object addSubProgramNameDuration() {
        List<ProgramDurationTimeEntity> insertList = new ArrayList();
        QueryWrapper<MachineToolStatus> wrapper = new QueryWrapper<>();
        wrapper.ge("time", 1);
        List<MachineToolStatus> machineToolStatusList = machineToolStatusMapper.selectList(wrapper);
        if (CollectionUtil.isNotEmpty(machineToolStatusList)) {
            machineToolStatusList
                    .stream()
                    .filter(machineToolStatus -> StringUtils.isNotBlank(machineToolStatus.getProgram()))
                    .collect(Collectors.toList());
            for (MachineToolStatus machineToolStatus : machineToolStatusList) {
                buildInsertDurationList(insertList, machineToolStatus.getProgram(), machineToolStatus.getSnCode(), machineToolStatus.getTime());
            }
            if (CollectionUtil.isNotEmpty(insertList)) {
                programDurationTimeMapper.insertBatchSomeColumn(insertList);
            }
        }
        return null;
    }

    public void buildInsertDurationList(List<ProgramDurationTimeEntity> insertDurationList, String program, String snCode, Long time) {
        ProgramDurationTimeEntity programDurationTimeEntity = new ProgramDurationTimeEntity();
        programDurationTimeEntity.setTime(ObjectUtil.isNotNull(time) ? time : 0);
        programDurationTimeEntity.setCreateTime(new Date());
        programDurationTimeEntity.setMachineToolName(warehouseRespository.getNameBySnCode(snCode));
        //处理program名
        String[] split = program.split("\\/");
        String[] split1 = program.split("\\\\");
        String subProgramName = "";
        if (split.length > split1.length) {
            subProgramName = split[split.length - 1];
        } else {
            subProgramName = split1[split1.length - 1];
        }
        programDurationTimeEntity.setProgram(subProgramName);
        insertDurationList.add(programDurationTimeEntity);
    }

    public void exportSubprogramList(HttpServletResponse response, ExportSubprogramListReq exportSubprogramListReq) {
        String outputFileName = exportSubprogramListReq.getProgramEntity().getProgramNum().trim() + "程序看板";
        CommonUtil.exportExcelFile(exportSubprogramListReq, "/template/子程序导出模板.xlsx", response, outputFileName);
    }

    public Object abutmentSubProgramTest() {
        QueryWrapper<ProductionEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("process_status", 0);
        List<ProductionEntity> productionEntities = productionMapper.selectList(wrapper);
        if (CollectionUtil.isNotEmpty(productionEntities)) {
            List<String> materialNos = productionEntities.stream().map(ProductionEntity::getMaterialNo).collect(Collectors.toList());
            abutmentSubProgramReload(materialNos);
        }
        return Boolean.TRUE;
    }


    public Object editSubPrograms(EditSubprogramReq editSubprogramReq) {
        if (CollectionUtil.isNotEmpty(editSubprogramReq.getSubProgramEntities())) {
            editSubprogramReq
                    .getSubProgramEntities()
                    .forEach(subProgramEntity ->
            {
                if (StringUtils.isNotBlank(subProgramEntity.getShankModel())) {
                    QueryWrapper<ShankModelMappingEntity> wrapper = new QueryWrapper<>();
                    wrapper.eq("old_model", subProgramEntity.getShankModel());
                    ShankModelMappingEntity shankModelMappingEntity = shankModelMappingMapper.selectOne(wrapper);
                    if(ObjectUtil.isNotNull(shankModelMappingEntity)){
                        subProgramEntity.setShankModel(shankModelMappingEntity.getNewModel());
                    }
                }
            });
            subProgramMapper.updateBatchById( editSubprogramReq.getSubProgramEntities());
        }
        return Boolean.TRUE;
    }

    public Object querySubProgramVersion(QuerySubprogramVersionReq querySubprogramVersionReq) {
        QueryWrapper<SubProgramEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("program_code" , querySubprogramVersionReq.getProgramCode());
        List<SubProgramEntity> subProgramEntityList = subProgramMapper.selectList(wrapper);
        if(CollectionUtil.isNotEmpty(subProgramEntityList)){
            List<Integer> versionList = subProgramEntityList.stream().map(SubProgramEntity::getVersion).collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(versionList)){
                return versionList
                        .stream()
                        .distinct()
                        .sorted()
                        .collect(Collectors.toList());
            }
        }
        return new ArrayList<>();
    }

    public Object addOrEditSubProgramReload1(AddOrEditSubProgramReloadReq addOrEditSubProgramReloadReq) {
        QueryWrapper<EquipmentSubprogramMappingEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("program_code", addOrEditSubProgramReloadReq.getProgramCode());
        wrapper.eq("equipment_id", addOrEditSubProgramReloadReq.getEquipmentId());
        EquipmentSubprogramMappingEntity equipmentSubprogramMappingEntity = equipmentSubprogramMappingMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(equipmentSubprogramMappingEntity)) {
            return new ProgramVo();
        }
        // 构造编辑，修改，删除业务所需要的参数
        QuerySubProgramReq querySubProgramReq = new QuerySubProgramReq();
        querySubProgramReq.setVersion(addOrEditSubProgramReloadReq.getProgramVersion());
        querySubProgramReq.setProgramCode(addOrEditSubProgramReloadReq.getProgramCode());
        querySubProgramReq.setEquipmentId(addOrEditSubProgramReloadReq.getEquipmentId());
        querySubProgramReq.setFlag(0);
        List<SubProgramEntity> originalList = querySubProgramList(querySubProgramReq);
        List<SubProgramEntity> updateList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(addOrEditSubProgramReloadReq.getIntegrationToolCodeList())){
            Map<String, EditIntegrationSubProgramReq> groupByToolCodeMap = addOrEditSubProgramReloadReq.getIntegrationToolCodeList()
                    .stream()
                    .collect(Collectors.toMap(EditIntegrationSubProgramReq::getToolCode, editIntegrationSubProgramReq -> editIntegrationSubProgramReq));
            for (SubProgramEntity subProgramEntity : originalList) {
                EditIntegrationSubProgramReq editIntegrationSubProgramReq = groupByToolCodeMap.get(subProgramEntity.getToolCode());
                if(ObjectUtil.isNotNull(editIntegrationSubProgramReq)){
                    subProgramEntity.setToolCode(editIntegrationSubProgramReq.getToolCode());
                    subProgramEntity.setToolModel(editIntegrationSubProgramReq.getToolModel());
                    subProgramEntity.setShankModel(editIntegrationSubProgramReq.getShankModel());
                    subProgramEntity.setVersion(addOrEditSubProgramReloadReq.getNewProgramVersion());
                    updateList.add(subProgramEntity);
                }
            }
            SubProgramManageLogic subProgramManageLogic = new SubProgramManageLogic(new ArrayList<>(), updateList);
            subProgramManageLogic.buildSubProgramDo();
            SubProgramDo subProgramDo = subProgramManageLogic.getSubProgramDo();
            // 数据持久化
            persistance(subProgramDo);
            // 暂时不涉及升级版本的问题
            //return new ProgramVo(addOrEditSubProgramReloadReq.getProgramCode(), addOrEditSubProgramReloadReq.getProgramVersion());
        }
        return new ProgramVo(addOrEditSubProgramReloadReq.getProgramCode() , addOrEditSubProgramReloadReq.getProgramVersion());
    }


    public Object addOrEditSubProgram1(AddOrEditSubProgramReloadReq addOrEditSubProgramReloadReq) {
//        QueryWrapper<EquipmentSubprogramMappingEntity> wrapper = new QueryWrapper<>();
//        wrapper.eq("program_code", addOrEditSubProgramReq.getProgramCode());
//        wrapper.eq("equipment_id", addOrEditSubProgramReq.getEquipmentId());
//        EquipmentSubprogramMappingEntity equipmentSubprogramMappingEntity = equipmentSubprogramMappingMapper.selectOne(wrapper);
//        if (ObjectUtil.isNull(equipmentSubprogramMappingEntity)) {
//            return new ProgramVo();
//        }
//        // 构造编辑，修改，删除业务所需要的参数
//        List<SubProgramEntity> originSubProgramList = querySubprogramList(addOrEditSubProgramReq.getProgramCode(), addOrEditSubProgramReq.getProgramVersion());
//        List<SubProgramEntity> updateSubProgramList = transferUpdateSubProgramList(addOrEditSubProgramReq, equipmentSubprogramMappingEntity.getProgramCode());
//        SubProgramManageLogic subProgramManageLogic = new SubProgramManageLogic(originSubProgramList, updateSubProgramList);
//        subProgramManageLogic.buildSubProgramDo();
//        SubProgramDo subProgramDo = subProgramManageLogic.getSubProgramDo();
//        // 数据持久化
//        persistance(subProgramDo);
//        // 暂时不涉及升级版本的问题
//        return new ProgramVo(addOrEditSubProgramReq.getProgramCode(), addOrEditSubProgramReq.getProgramVersion());

        QueryWrapper<EquipmentSubprogramMappingEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("program_code", addOrEditSubProgramReloadReq.getProgramCode());
        wrapper.eq("equipment_id", addOrEditSubProgramReloadReq.getEquipmentId());
        EquipmentSubprogramMappingEntity equipmentSubprogramMappingEntity = equipmentSubprogramMappingMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(equipmentSubprogramMappingEntity)) {
            return new ProgramVo();
        }
        // 构造编辑，修改，删除业务所需要的参数
        QuerySubProgramReq querySubProgramReq = new QuerySubProgramReq();
        querySubProgramReq.setVersion(addOrEditSubProgramReloadReq.getProgramVersion());
        querySubProgramReq.setProgramCode(addOrEditSubProgramReloadReq.getProgramCode());
        querySubProgramReq.setEquipmentId(addOrEditSubProgramReloadReq.getEquipmentId());
        querySubProgramReq.setFlag(0);
        List<SubProgramEntity> originalList = querySubProgramList(querySubProgramReq);
        List<SubProgramEntity> updateList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(addOrEditSubProgramReloadReq.getIntegrationToolCodeList())){
            Map<String, EditIntegrationSubProgramReq> groupByToolCodeMap = addOrEditSubProgramReloadReq.getIntegrationToolCodeList()
                    .stream()
                    .collect(Collectors.toMap(EditIntegrationSubProgramReq::getToolCode, editIntegrationSubProgramReq -> editIntegrationSubProgramReq));
            for (SubProgramEntity subProgramEntity : originalList) {
                EditIntegrationSubProgramReq editIntegrationSubProgramReq = groupByToolCodeMap.get(subProgramEntity.getToolCode());
                if(ObjectUtil.isNotNull(editIntegrationSubProgramReq)){
                    subProgramEntity.setToolCode(editIntegrationSubProgramReq.getNewToolCode());
                    subProgramEntity.setToolModel(editIntegrationSubProgramReq.getToolModel());
                    subProgramEntity.setShankModel(editIntegrationSubProgramReq.getShankModel());
                    updateList.add(subProgramEntity);
                }
            }
            SubProgramManageLogic subProgramManageLogic = new SubProgramManageLogic(originalList, updateList);
            subProgramManageLogic.buildSubProgramDo();
            SubProgramDo subProgramDo = subProgramManageLogic.getSubProgramDo();
            // 数据持久化
            persistance(subProgramDo);
            // 暂时不涉及升级版本的问题
            //return new ProgramVo(addOrEditSubProgramReloadReq.getProgramCode(), addOrEditSubProgramReloadReq.getProgramVersion());
        }
        return new ProgramVo(addOrEditSubProgramReloadReq.getProgramCode() , addOrEditSubProgramReloadReq.getProgramVersion());
    }


//    public Object abutmentSubProgram() {
////        String get = HttpUtil.get(UrlConstant.PROCESS_MANAGEMENT_SYNC_URL + "/abutmentSubProgram");
//        List<AbutmentProgramEntity> abutmentPrograms = testService.test1();
//        if(CollectionUtil.isNotEmpty(abutmentPrograms)){
//            //List<AbutmentProgram> abutmentPrograms = JSONArray.parseArray(get, AbutmentProgram.class);
//            if(CollectionUtil.isNotEmpty(abutmentPrograms)){
//                List<ProgramEntity> addProgramEntities = new ArrayList<>();
//                List<ProgramEntity> updateProgramEntities = new ArrayList<>();
//                List<SubProgramEntity> addSubProgramEntities = new ArrayList<>();
//                List<Integer> deleteSubProgramEntities = new ArrayList<>();
//                abutmentPrograms.forEach(abutmentProgram -> {
//                    //查询数据库中是否有该条主程序记录
//                    QueryWrapper<ProgramEntity> wrapper = new QueryWrapper<>();
//                    wrapper.eq("program_cn" , abutmentProgram.getProgramCn());
//                    ProgramEntity existProgramEntity = programMapper.selectOne(wrapper);
//                    String programCode = "program-"+UUIDUtil.getUUID();
//                    if(ObjectUtil.isNotNull(existProgramEntity)){
//                        programCode = existProgramEntity.getCode();
//                        existProgramEntity.setProgramNum(abutmentProgram.getMaterialNo());
//                        existProgramEntity.setName(abutmentProgram.getProductionNum());
//                        existProgramEntity.setVersion(CommonConstant.INIT_VERSION);
//                        BeanUtil.copyProperties(abutmentProgram , existProgramEntity);
//                        updateProgramEntities.add(existProgramEntity);
//                        QueryWrapper<SubProgramEntity> subProgramWrapper = new QueryWrapper<>();
//                        subProgramWrapper.eq("program_code" , programCode);
//                        List<SubProgramEntity> subProgramEntityList = subProgramMapper.selectList(subProgramWrapper);
//                        if(CollectionUtil.isNotEmpty(subProgramEntityList)){
//                            deleteSubProgramEntities.addAll(subProgramEntityList.stream().map(SubProgramEntity::getId).collect(Collectors.toList()));
//                        }
//                    }else{
//                        ProgramEntity programEntity = new ProgramEntity();
//                        programEntity.setCode(programCode);
//                        programEntity.setProgramNum(abutmentProgram.getMaterialNo());
//                        programEntity.setName(abutmentProgram.getProductionNum());
//                        programEntity.setVersion(CommonConstant.INIT_VERSION);
//                        BeanUtil.copyProperties(abutmentProgram , programEntity);
//                        addProgramEntities.add(programEntity);
//                    }
//                    List<AbutmentSubProgramEntity> connectSubProgram = abutmentProgram.getConnectSubProgram();
//                    if(CollectionUtil.isNotEmpty(connectSubProgram)){
//                        //根据关联机床构建子程序
//                        List<Integer> equipmentIds = equipmentGroupRepository.selectEquipmentIds();
//                        if(ObjectUtil.isNotNull(abutmentProgram.getEquipment())||StringUtil.isNotEmpty(abutmentProgram.getEquipment())){
//                            //TO DO主程序适用机床不为空，则根据印射规则获取机床id
//                        }
//                        for (int i = 0; i < connectSubProgram.size(); i++) {
//                            for (int j = 0; j < equipmentIds.size(); j++) {
//                                AbutmentSubProgramEntity abutmentSubProgram = connectSubProgram.get(i);
//                                SubProgramEntity subProgramEntity = new SubProgramEntity();
//                                subProgramEntity.setCode("subProgram"+"-"+UUIDUtil.getUUID());
//                                subProgramEntity.setProgramCode(programCode);
//                                subProgramEntity.setVersion(CommonConstant.INIT_VERSION);
//                                subProgramEntity.setEquipmentId(equipmentIds.get(j));
//                                subProgramEntity.setEquipmentGroupType(equipmentGroupRepository.selectGroupTypeByEquipmentId(equipmentIds.get(j)));
//                                subProgramEntity.setRpm(Integer.valueOf(abutmentSubProgram.getRpm()));
//                                subProgramEntity.setFeed(new BigDecimal(abutmentSubProgram.getFeed()));
//                                subProgramEntity.setExtension(new BigDecimal(abutmentSubProgram.getExtension()));
//                                //BeanUtil.copyProperties(connectSubProgram.get(i) , subProgramEntity);
//                                addSubProgramEntities.add(subProgramEntity);
//                            }
//                        }
//                    }
//                });
//                //批量新增主程序
//                if(CollectionUtil.isNotEmpty(addProgramEntities)){
//                    programMapper.insertBatchSomeColumn(addProgramEntities);
//                }
//                //批量修改主程序
//                if(CollectionUtil.isNotEmpty(updateProgramEntities)){
//                    programMapper.updateBatchById(updateProgramEntities);
//                }
//                //批量删除子程序
//                if(CollectionUtil.isNotEmpty(deleteSubProgramEntities)){
//                    programMapper.deleteBatchIds(deleteSubProgramEntities);
//                }
//                //批量新增子程序
//                if(CollectionUtil.isNotEmpty(addSubProgramEntities)){
//                    subProgramMapper.insertBatchSomeColumn(addSubProgramEntities);
//                }
//            }
//        }
//        return Boolean.TRUE;
//    }
//
//    public Object abutmentSubProgramReload(List<String> materialNos) {
////        String get = HttpUtil.get(UrlConstant.PROCESS_MANAGEMENT_SYNC_URL + "/abutmentSubProgram");
//        List<AbutmentProgramEntity> abutmentPrograms = testService.test1(materialNos);
//        if(CollectionUtil.isNotEmpty(abutmentPrograms)){
//            //List<AbutmentProgram> abutmentPrograms = JSONArray.parseArray(get, AbutmentProgram.class);
//            if(CollectionUtil.isNotEmpty(abutmentPrograms)){
//                List<ProgramEntity> addProgramEntities = new ArrayList<>();
//                List<ProgramEntity> updateProgramEntities = new ArrayList<>();
//                List<SubProgramEntity> addSubProgramEntities = new ArrayList<>();
//                List<Integer> deleteSubProgramEntities = new ArrayList<>();
//                abutmentPrograms.forEach(abutmentProgram -> {
//                    //查询数据库中是否有该条主程序记录
//                    QueryWrapper<ProgramEntity> wrapper = new QueryWrapper<>();
//                    wrapper.eq("program_cn" , abutmentProgram.getProgramCn());
//                    ProgramEntity existProgramEntity = programMapper.selectOne(wrapper);
//                    String programCode = "program-"+UUIDUtil.getUUID();
//                    if(ObjectUtil.isNotNull(existProgramEntity)){
//                        programCode = existProgramEntity.getCode();
//                        existProgramEntity.setProgramNum(abutmentProgram.getMaterialNo());
//                        existProgramEntity.setName(abutmentProgram.getProductionNum());
//                        existProgramEntity.setVersion(CommonConstant.INIT_VERSION);
//                        BeanUtil.copyProperties(abutmentProgram , existProgramEntity);
//                        updateProgramEntities.add(existProgramEntity);
//                        QueryWrapper<SubProgramEntity> subProgramWrapper = new QueryWrapper<>();
//                        subProgramWrapper.eq("program_code" , programCode);
//                        List<SubProgramEntity> subProgramEntityList = subProgramMapper.selectList(subProgramWrapper);
//                        if(CollectionUtil.isNotEmpty(subProgramEntityList)){
//                            deleteSubProgramEntities.addAll(subProgramEntityList.stream().map(SubProgramEntity::getId).collect(Collectors.toList()));
//                        }
//                    }else{
//                        ProgramEntity programEntity = new ProgramEntity();
//                        programEntity.setCode(programCode);
//                        programEntity.setProgramNum(abutmentProgram.getMaterialNo());
//                        programEntity.setName(abutmentProgram.getProductionNum());
//                        programEntity.setVersion(CommonConstant.INIT_VERSION);
//                        BeanUtil.copyProperties(abutmentProgram , programEntity);
//                        addProgramEntities.add(programEntity);
//                    }
//                    List<AbutmentSubProgramEntity> connectSubProgram = abutmentProgram.getConnectSubProgram();
//                    if(CollectionUtil.isNotEmpty(connectSubProgram)){
//                        //根据关联机床构建子程序
//                        List<Integer> equipmentIds = equipmentGroupRepository.selectEquipmentIds();
//                        if(ObjectUtil.isNotNull(abutmentProgram.getEquipment())||StringUtil.isNotEmpty(abutmentProgram.getEquipment())){
//                            //TO DO主程序适用机床不为空，则根据印射规则获取机床id
//                        }
//                        for (int i = 0; i < connectSubProgram.size(); i++) {
//                            for (int j = 0; j < equipmentIds.size(); j++) {
//                                AbutmentSubProgramEntity abutmentSubProgram = connectSubProgram.get(i);
//                                SubProgramEntity subProgramEntity = new SubProgramEntity();
//                                subProgramEntity.setCode("subProgram"+"-"+UUIDUtil.getUUID());
//                                subProgramEntity.setProgramCode(programCode);
//                                subProgramEntity.setVersion(CommonConstant.INIT_VERSION);
//                                subProgramEntity.setEquipmentId(equipmentIds.get(j));
//                                subProgramEntity.setEquipmentGroupType(equipmentGroupRepository.selectGroupTypeByEquipmentId(equipmentIds.get(j)));
//                                subProgramEntity.setRpm(Integer.valueOf(abutmentSubProgram.getRpm()));
//                                subProgramEntity.setFeed(new BigDecimal(abutmentSubProgram.getFeed()));
//                                subProgramEntity.setExtension(new BigDecimal(abutmentSubProgram.getExtension()));
//                                //BeanUtil.copyProperties(connectSubProgram.get(i) , subProgramEntity);
//                                addSubProgramEntities.add(subProgramEntity);
//                            }
//                        }
//                    }
//                });
//                //批量新增主程序
//                if(CollectionUtil.isNotEmpty(addProgramEntities)){
//                    programMapper.insertBatchSomeColumn(addProgramEntities);
//                }
//                //批量修改主程序
//                if(CollectionUtil.isNotEmpty(updateProgramEntities)){
//                    programMapper.updateBatchById(updateProgramEntities);
//                }
//                //批量删除子程序
//                if(CollectionUtil.isNotEmpty(deleteSubProgramEntities)){
//                    programMapper.deleteBatchIds(deleteSubProgramEntities);
//                }
//                //批量新增子程序
//                if(CollectionUtil.isNotEmpty(addSubProgramEntities)){
//                    subProgramMapper.insertBatchSomeColumn(addSubProgramEntities);
//                }
//            }
//        }
//        return Boolean.TRUE;
//    }
}
